package com.smart.community.property.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.dto.property.PropertyCompanyQueryDTO;
import com.smart.community.commons.entity.property.PropertyCompany;
import com.smart.community.commons.entity.property.PropertyCompanyCommunity;
import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.commons.enums.RoleCodeEnum;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.region.dto.RegionDTO;
import com.smart.community.feign.region.service.RegionFeignService;
import com.smart.community.feign.region.service.RegionDataFeignService;
import com.smart.community.feign.user.dto.UserDTO;
import com.smart.community.feign.user.service.UserFeignService;
import com.smart.community.property.dto.PropertyCompanyAuditDTO;
import com.smart.community.property.dto.PropertyCompanyDTO;
import com.smart.community.property.mapper.PropertyCompanyMapper;
import com.smart.community.property.mapper.UserPropertyCompanyMapper;
import com.smart.community.property.service.DataScopeService;
import com.smart.community.property.service.IPropertyCompanyCommunityService;
import com.smart.community.property.service.IPropertyCompanyService;
import com.smart.community.property.service.PropertyCompanyPermissionCacheService;
import com.smart.community.property.vo.PropertyCompanyVO;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 物业公司服务实现类
 * 
 * @author Wu.Liang
 * @since 2025-06-29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PropertyCompanyServiceImpl extends ServiceImpl<PropertyCompanyMapper, PropertyCompany>
		implements IPropertyCompanyService {

	private final RegionFeignService regionFeignClient;
	private final RegionDataFeignService regionDataFeignClient;

	private final UserFeignService userFeignService;

	@Autowired
	private UserPropertyCompanyMapper userPropertyCompanyMapper;
	@Autowired
	private PropertyCompanyPermissionCacheService permissionCacheService;
	@Autowired
	private DataScopeService dataScopeService;
	@Autowired
	private DataScopeService propertyCompanyDataScopeService;

	@Autowired
	private IPropertyCompanyCommunityService propertyCompanyCommunityService;

	@Override
	public Result<PropertyCompanyVO> getPropertyCompany(Long id) throws Exception {
		log.info("查询物业公司详情，ID：{}", id);
		PropertyCompany propertyCompany = this.getById(id);
		if (propertyCompany == null) {
			return Result.fail("物业公司不存在");
		}

		PropertyCompanyVO vo = convertToVO(propertyCompany);
		return Result.success(vo);
	}

	@Override
	public Result<PageResult<PropertyCompanyVO>> getPropertyCompanyList(PropertyCompanyQueryDTO queryDTO)
			throws Exception {
		log.info("查询物业公司列表，参数：{}", queryDTO);
		Long currentUserId = SecurityUtils.getCurrentUserId();
		log.info("当前用户ID：{}，开始权限检查", currentUserId);

		// 构建查询条件
		QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();

		// 添加查询条件
		if (StringUtils.hasText(queryDTO.getCompanyName())) {
			queryWrapper.like("company_name", queryDTO.getCompanyName());
		}
		if (StringUtils.hasText(queryDTO.getCompanyCode())) {
			queryWrapper.like("company_code", queryDTO.getCompanyCode());
		}
		// TODO: 修复getContactPerson方法问题
		// if (StringUtils.hasText(queryDTO.getContactPerson())) {
		// queryWrapper.like("contact_person", queryDTO.getContactPerson());
		// }
		if (StringUtils.hasText(queryDTO.getContactPhone())) {
			queryWrapper.like("contact_phone", queryDTO.getContactPhone());
		}
		if (StringUtils.hasText(queryDTO.getQualificationLevel())) {
			queryWrapper.eq("qualification_level", queryDTO.getQualificationLevel());
		}
		if (queryDTO.getStatus() != null) {
			queryWrapper.eq("status", queryDTO.getStatus());
		}
		if (queryDTO.getAuditStatus() != null) {
			queryWrapper.eq("audit_status", queryDTO.getAuditStatus());
		}

		// 添加数据权限过滤
		// 直接使用SecurityUtils判断超级管理员，避免缓存问题
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		boolean isSuperAdmin = dataScopeInfo.isSuperAdmin();
		log.info("用户{}是否为超级管理员：{}", currentUserId, isSuperAdmin);

		if (isSuperAdmin) {
			// 超级管理员有所有权限
			log.info("超级管理员用户{}，可以查看所有物业公司", currentUserId);
		} else {
			// 非超级管理员需要进行数据权限过滤
			List<Long> propertyCompanyIds = dataScopeInfo.getPropertyCompanyIds();
			log.info("用户{}的物业公司权限ID列表：{}", currentUserId, propertyCompanyIds);

			if (propertyCompanyIds != null && !propertyCompanyIds.isEmpty()) {
				// 用户有物业公司权限，按权限过滤
				queryWrapper.in("id", propertyCompanyIds);
				log.info("根据用户权限过滤物业公司，ID列表：{}", propertyCompanyIds);
			} else {
				// 用户没有任何物业公司权限，返回空结果
				log.warn("用户{}没有物业公司权限，返回空结果", currentUserId);
				// 返回空的分页结果
				PageResult<PropertyCompanyVO> emptyResult = PageResult.of(Math.toIntExact(queryDTO.getCurrent()),
						Math.toIntExact(queryDTO.getSize()), 0L, new ArrayList<>());
				return Result.success(emptyResult);
			}
		}

		// 排序
		queryWrapper.orderByDesc("create_time");

		// 分页查询
		Page<PropertyCompany> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
		IPage<PropertyCompany> result = this.page(page, queryWrapper);

		// 转换为VO
		List<PropertyCompanyVO> voList = result.getRecords().stream().map(this::convertToVO)
				.collect(Collectors.toList());

		PageResult<PropertyCompanyVO> pageResult = PageResult.of(Math.toIntExact(result.getCurrent()),
				Math.toIntExact(result.getSize()), result.getTotal(), voList);

		return Result.success(pageResult);
	}

	@Override
	public Result<PropertyCompanyVO> getCurrentUserPropertyCompany() throws Exception {
		log.info("获取当前用户的物业公司信息");
		Long userId = SecurityUtils.getCurrentUserId();
		List<PropertyCompany> userCompanies = getUserPropertyCompaniesInternal(userId);

		if (userCompanies.isEmpty()) {
			return Result.fail("用户未关联物业公司");
		}

		// 返回第一个关联的物业公司
		PropertyCompanyVO vo = convertToVO(userCompanies.get(0));
		return Result.success(vo);
	}

	@Override
	@CacheEvict(value = { "propertyCompany", "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> updateCurrentUserPropertyCompany(PropertyCompanyDTO propertyCompanyDTO) throws Exception {
		log.info("更新当前用户的物业公司信息，参数：{}", propertyCompanyDTO);
		Long userId = SecurityUtils.getCurrentUserId();
		List<PropertyCompany> userCompanies = getUserPropertyCompaniesInternal(userId);

		if (userCompanies.isEmpty()) {
			return Result.fail("用户未关联物业公司");
		}

		// 更新第一个关联的物业公司
		PropertyCompany existingCompany = userCompanies.get(0);
		BeanUtils.copyProperties(propertyCompanyDTO, existingCompany);
		existingCompany.setUpdateBy(userId);
		existingCompany.setUpdateTime(LocalDateTime.now());

		boolean success = this.updateById(existingCompany);
		if (success) {
			log.info("更新当前用户物业公司信息成功");
			return Result.success();
		} else {
			return Result.fail("更新失败");
		}
	}

	@Override
	@CacheEvict(value = { "propertyCompany", "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> updatePropertyCompany(Long id, PropertyCompanyDTO propertyCompanyDTO) throws Exception {
		log.info("更新物业公司，ID：{}，参数：{}", id, propertyCompanyDTO);
		// 检查物业公司是否存在
		PropertyCompany existingCompany = this.getById(id);
		if (existingCompany == null) {
			return Result.fail("物业公司不存在");
		}

		// 检查公司编码是否已存在
		if (isCompanyCodeExists(propertyCompanyDTO.getCompanyCode(), id)) {
			return Result.fail("公司编码已存在");
		}

		// 更新实体
		BeanUtils.copyProperties(propertyCompanyDTO, existingCompany);
		existingCompany.setUpdateBy(SecurityUtils.getCurrentUserId());
		existingCompany.setUpdateTime(LocalDateTime.now());

		boolean success = this.updateById(existingCompany);
		if (success) {
			log.info("更新物业公司成功，ID：{}", id);
			return Result.success();
		} else {
			return Result.fail("更新失败");
		}
	}

	@Override
	public List<Object> getAvailableCommunities(Long propertyCompanyId, String searchKeyword) throws Exception {
		log.info("获取可分配的社区，物业公司ID：{}，搜索关键词：{}", propertyCompanyId, searchKeyword);
		try {
			// 调用物业公司社区关联服务获取可分配的社区
			List<Object> communities = propertyCompanyCommunityService.getAvailableCommunities(propertyCompanyId,
					searchKeyword);

			return communities;
		} catch (Exception e) {
			log.warn("获取可分配的社区失败，物业公司ID：{}", propertyCompanyId, e);
			return new ArrayList<>();
		}
	}

	@Override
	public List<PropertyCompanyVO> getPropertyCompanyListForSelect() throws Exception {
		log.info("获取物业公司列表（用于下拉选择）");
		try {
			Long currentUserId = SecurityUtils.getCurrentUserId();

			QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("status", SystemStatusEnum.ENABLED.getCode());
			queryWrapper.eq("audit_status", SystemStatusEnum.AUDIT_APPROVED.getCode());

			// 添加数据权限过滤
			if (!SecurityUtils.hasRole(RoleCodeEnum.SUPER_ADMIN.getCode())) {
				List<Long> propertyCompanyIds = permissionCacheService.getCurrentUserPropertyCompanyIds(currentUserId);
				if (propertyCompanyIds != null && !propertyCompanyIds.isEmpty()) {
					queryWrapper.in("id", propertyCompanyIds);
				}
			}

			queryWrapper.orderByAsc("company_name");

			List<PropertyCompany> companies = this.list(queryWrapper);
			return companies.stream().map(this::convertToVO).collect(Collectors.toList());
		} catch (Exception e) {
			log.warn("获取物业公司列表失败", e);
			return new ArrayList<>();
		}
	}

	@Override
	public List<Object> getAssignedCommunities(Long propertyCompanyId, String searchKeyword) throws Exception {
		log.info("获取物业公司已分配的社区，物业公司ID：{}，搜索关键词：{}", propertyCompanyId, searchKeyword);
		try {
			// 调用物业公司社区关联服务获取已分配的社区
			List<PropertyCompanyCommunity> communities = propertyCompanyCommunityService
					.getPropertyCompanyCommunities(propertyCompanyId);

			List<Map<String, Object>> assignedCommunities = new ArrayList<>();

			for (PropertyCompanyCommunity community : communities) {
				Map<String, Object> communityMap = new HashMap<>();
				communityMap.put("id", community.getCommunityId());

				// 调用区域服务获取社区详细信息
				try {
					com.smart.community.feign.region.dto.CommunityInfoDTO communityInfo = 
						regionDataFeignClient.getCommunityById(community.getCommunityId());

					if (communityInfo != null) {
						communityMap.put("communityName", communityInfo.getCommunityName());
						communityMap.put("communityCode", communityInfo.getCommunityCode());
						communityMap.put("address", communityInfo.getAddress() != null ? communityInfo.getAddress() : "");

						// 获取区域完整路径信息
						List<RegionDTO> pathResultData = regionFeignClient.getRegionPath(communityInfo.getRegionId());
						if (pathResultData != null && pathResultData.size() > 0) {
							String regionFullName = pathResultData.stream().map(RegionDTO::getRegionName)
									.collect(Collectors.joining(" / "));
							communityMap.put("regionFullName", regionFullName);
						} else {
							communityMap.put("regionFullName", communityInfo.getCommunityName());
						}
					} else {
						// 降级处理：使用基本信息
						communityMap.put("communityName", "社区" + community.getCommunityId());
						communityMap.put("communityCode", "COMM" + community.getCommunityId());
						communityMap.put("address", "地址信息");
						communityMap.put("regionFullName", "区域信息");
					}
				} catch (Exception e) {
					log.warn("获取社区详细信息失败，社区ID：{}", community.getCommunityId(), e);
					// 降级处理：使用基本信息
					communityMap.put("communityName", "社区" + community.getCommunityId());
					communityMap.put("communityCode", "COMM" + community.getCommunityId());
					communityMap.put("address", "地址信息");
					communityMap.put("regionFullName", "区域信息");
				}

				assignedCommunities.add(communityMap);
			}

			// 如果有搜索关键词，进行过滤
			if (StringUtils.hasText(searchKeyword)) {
				assignedCommunities = assignedCommunities.stream().filter(communityMap -> {
					String communityName = (String) communityMap.get("communityName");
					String regionFullName = (String) communityMap.get("regionFullName");
					return (communityName != null && communityName.toLowerCase().contains(searchKeyword.toLowerCase()))
							|| (regionFullName != null
									&& regionFullName.toLowerCase().contains(searchKeyword.toLowerCase()));
				}).collect(Collectors.toList());
			}

			log.info("获取物业公司已分配的社区成功，物业公司ID：{}，社区数量：{}", propertyCompanyId, assignedCommunities.size());
			return new ArrayList<>(assignedCommunities);

		} catch (Exception e) {
			log.warn("获取物业公司已分配的社区失败，物业公司ID：{}", propertyCompanyId, e);
			return new ArrayList<>();
		}
	}

	@Override
	@CacheEvict(value = { "propertyCompany", "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> deletePropertyCompany(Long id) throws Exception {
		log.info("删除物业公司，ID：{}", id);
		// 检查物业公司是否存在
		PropertyCompany propertyCompany = this.getById(id);
		if (propertyCompany == null) {
			return Result.fail("物业公司不存在");
		}

		// 逻辑删除
		boolean success = this.removeById(id);
		if (success) {
			log.info("删除物业公司成功，ID：{}", id);
			return Result.success();
		} else {
			return Result.fail("删除失败");
		}
	}

	@Override
	@CacheEvict(value = { "propertyCompany", "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> auditPropertyCompany(Long id, PropertyCompanyAuditDTO auditDTO) throws Exception {
		log.info("审核物业公司，ID：{}，参数：{}", id, auditDTO);
		// 检查权限（只有超级管理员可以审核）
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		if (!dataScopeInfo.isSuperAdmin()) {
			return Result.fail("权限不足");
		}

		// 检查物业公司是否存在
		PropertyCompany propertyCompany = this.getById(id);
		if (propertyCompany == null) {
			return Result.fail("物业公司不存在");
		}

		// 更新审核信息
		propertyCompany.setAuditStatus(auditDTO.getAuditStatus());
		propertyCompany.setAuditRemark(auditDTO.getAuditRemark());
		propertyCompany.setAuditBy(SecurityUtils.getCurrentUserId());
		propertyCompany.setAuditTime(LocalDateTime.now());

		// 如果审核通过，更新状态为启用
		if (SystemStatusEnum.AUDIT_APPROVED.getCode().equals(auditDTO.getAuditStatus())) {
			propertyCompany.setStatus(SystemStatusEnum.ENABLED.getCode());
		} else if (SystemStatusEnum.AUDIT_REJECTED.getCode().equals(auditDTO.getAuditStatus())) {
			propertyCompany.setStatus(SystemStatusEnum.DISABLED.getCode());
		}

		boolean success = this.updateById(propertyCompany);
		if (success) {
			log.info("审核物业公司成功，ID：{}", id);
			if (SystemStatusEnum.ENABLED.getCode().equals(propertyCompany.getStatus())) {
				/* ------------------------ 以下都需要调用用户服务的Feign接口来实现 TODO ------------------------ */
				// 根据物业公司的联系人电话"contactPhone"查询用户表"sc_user"（Feign方式调用用户服务），如果用户表中此手机号有用户，则获取此用户对象，`user_type`设置为`RoleCodeEnum`中的`PROPERTY_ADMIN`的`code`
				// 然后给此用户分配角色"物业管理员"(id=9)
				// 如果根据联系人电话查询不到用户，则需要新增物一个用户，`username`为联系人电话，`phone`为联系人电话,密码为联系人电话（按我们的加密方式加密），`user_type`为`RoleCodeEnum`中的`PROPERTY_ADMIN`的`code`
				// 新增的用户也需要关联角色"物业管理员"(id=9)
				try {
					// 获取物业公司联系人电话
					String contactPhone = propertyCompany.getContactPhone();
					if (StringUtils.hasText(contactPhone)) {
						log.info("开始处理物业公司联系人用户，联系人电话：{}", contactPhone);
						
						// 根据联系人电话查询用户
						UserDTO existingUser = null;
						try {
							existingUser = userFeignService.getUserByPhone(contactPhone);
						} catch (Exception feignException) {
							log.warn("调用用户服务查询用户失败，联系人电话：{}，错误：{}", contactPhone, feignException.getMessage());
							// 继续执行，尝试创建新用户
						}
						
						if (existingUser != null) {
							// 用户已存在，更新用户类型为物业管理员
							log.info("用户已存在，用户ID：{}，更新用户类型为物业管理员", existingUser.getId());
							try {
								existingUser.setUserType(RoleCodeEnum.PROPERTY_ADMIN.getCode());
								existingUser.setPropertyCompanyId(propertyCompany.getId());
								userFeignService.updateUser(existingUser);
								
								// 分配物业管理员角色（id=9）
								List<Long> roleIds = Arrays.asList(9L);
								userFeignService.assignUserRoles(existingUser.getId(), roleIds);
								log.info("已为用户分配物业管理员角色，用户ID：{}", existingUser.getId());

								// 更新用户和物业公司关联
								updateOrAddUserPropertyCompany(existingUser.getId(), propertyCompany.getId());
							} catch (Exception updateException) {
								log.warn("更新用户信息失败，用户ID：{}，错误：{}", existingUser.getId(), updateException.getMessage());
							}
						} else {
							// 用户不存在，创建新用户
							log.info("用户不存在，开始创建新用户，联系人电话：{}", contactPhone);
							
							try {
								// 创建用户DTO
								UserDTO newUser = new UserDTO();
								newUser.setUsername(contactPhone);
								newUser.setPhone(contactPhone);
								newUser.setRealName(propertyCompany.getContactPerson());
								newUser.setUserType(RoleCodeEnum.PROPERTY_ADMIN.getCode());
								newUser.setStatus(SystemStatusEnum.USER_NORMAL.getCode());
								newUser.setAuditStatus(SystemStatusEnum.AUDIT_APPROVED.getCode());
								newUser.setPropertyCompanyId(propertyCompany.getId());
								
								// 创建用户
								UserDTO createdUser = userFeignService.createUser(newUser);
								if (createdUser != null) {
									log.info("新用户创建成功，用户ID：{}", createdUser.getId());
									
									// 分配物业管理员角色（id=9）
									List<Long> roleIds = Arrays.asList(9L);
									userFeignService.assignUserRoles(createdUser.getId(), roleIds);
									log.info("已为新用户分配物业管理员角色，用户ID：{}", createdUser.getId());
									
									// 更新用户和物业公司关联
									updateOrAddUserPropertyCompany(createdUser.getId(), propertyCompany.getId());
								} else {
									log.warn("新用户创建失败，联系人电话：{}", contactPhone);
								}
							} catch (Exception createException) {
								log.warn("创建新用户失败，联系人电话：{}，错误：{}", contactPhone, createException.getMessage());
							}
						}
					} else {
						log.warn("物业公司联系人电话为空，跳过用户处理，物业公司ID：{}", id);
					}
				} catch (Exception e) {
					log.error("处理物业公司联系人用户时发生异常，物业公司ID：{}，异常信息：{}", id, e.getMessage(), e);
					// 不抛出异常，避免影响审核流程
				}
			}
			return Result.success();
		} else {
			return Result.fail("审核失败");
		}
	}

	@Override
	@GlobalTransactional
	public Result<String> assignCommunitiesToPropertyCompany(Long propertyCompanyId, List<Long> communityIds)
			throws Exception {
		log.info("为物业公司分配社区，物业公司ID：{}，社区ID列表：{}", propertyCompanyId, communityIds);
		// 只有超级管理员有分配权限
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		if (!dataScopeInfo.isSuperAdmin()) {
			return Result.fail("权限不足"); 
		}

		// 调用物业公司社区关联服务进行分配
		Result<String> result = propertyCompanyCommunityService.assignCommunitiesToPropertyCompany(propertyCompanyId,
				communityIds);
		return result;
	}

	@Override
	@CacheEvict(value = { "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> createPropertyCompany(PropertyCompanyDTO propertyCompanyDTO) throws Exception {
		log.info("新增物业公司，参数：{}", propertyCompanyDTO);
		// 检查公司编码是否已存在
		if (isCompanyCodeExists(propertyCompanyDTO.getCompanyCode(), null)) {
			return Result.fail("公司编码已存在");
		}

		// 转换为实体
		PropertyCompany propertyCompany = new PropertyCompany();
		BeanUtils.copyProperties(propertyCompanyDTO, propertyCompany);

		// 设置默认值
		propertyCompany.setStatus(SystemStatusEnum.DISABLED.getCode());
		propertyCompany.setAuditStatus(0); // 待审核
		propertyCompany.setCreateBy(SecurityUtils.getCurrentUserId());
		propertyCompany.setCreateTime(LocalDateTime.now());

		boolean success = this.save(propertyCompany);
		if (success) {
			log.info("新增物业公司成功，ID：{}", propertyCompany.getId());
			return Result.success();
		} else {
			return Result.fail("新增失败");
		}
	}
	
	@Override
	@CacheEvict(value = { "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
	public Result<Void> registerPropertyCompany(PropertyCompanyDTO propertyCompanyDTO) throws Exception {
		log.info("物业公司注册，参数：{}", propertyCompanyDTO);
		
		// 检查公司编码是否已存在
		if (isCompanyCodeExists(propertyCompanyDTO.getCompanyCode(), null)) {
			return Result.fail("公司编码已存在");
		}

		// 转换为实体
		PropertyCompany propertyCompany = new PropertyCompany();
		BeanUtils.copyProperties(propertyCompanyDTO, propertyCompany);

		// 设置注册时的默认值
		propertyCompany.setStatus(SystemStatusEnum.DISABLED.getCode()); // 状态为禁用
		propertyCompany.setAuditStatus(SystemStatusEnum.AUDIT_PENDING.getCode()); // 审核状态为待审核
		propertyCompany.setCreateTime(LocalDateTime.now());
		propertyCompany.setUpdateTime(LocalDateTime.now());
		propertyCompany.setDeleted(SystemStatusEnum.NOT_DELETED.getCode());
		propertyCompany.setVersion(SystemStatusEnum.ENABLED.getCode());
		// 注册时不需要设置createBy，因为这是公开注册接口

		boolean success = this.save(propertyCompany);
		if (success) {
			log.info("物业公司注册成功，ID：{}", propertyCompany.getId());
			return Result.success();
		} else {
			return Result.fail("注册失败");
		}
	}

	@Override
	public boolean hasViewPermission(Long userId) throws Exception {
		if (userId == null) {
			log.warn("用户ID为空，权限检查失败");
			return false;
		}

		log.info("开始检查用户 {} 的物业公司查看权限", userId);

		// 检查是否为超级管理员
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		boolean isSuperAdmin = dataScopeInfo.isSuperAdmin();
		log.info("用户 {} 超级管理员检查结果：{}", userId, isSuperAdmin);

		if (isSuperAdmin) {
			log.info("用户 {} 是超级管理员，拥有所有物业公司权限", userId);
			return true;
		}

		// 检查用户是否关联了物业公司
		List<PropertyCompany> propertyCompanies = getUserPropertyCompanies(userId);
		boolean hasPermission = !propertyCompanies.isEmpty();
		log.info("用户 {} 物业公司权限检查结果：{}，关联物业公司数量：{}", userId, hasPermission, propertyCompanies.size());
		return hasPermission;
	}

	@Override
	public boolean hasViewPermission(Long userId, Long propertyCompanyId) throws Exception {
		if (userId == null || propertyCompanyId == null) {
			return false;
		}

		// 检查是否为超级管理员
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		if (dataScopeInfo.isSuperAdmin()) {
			return true;
		}

		// 检查用户是否有该物业公司的权限
		List<PropertyCompany> propertyCompanies = getUserPropertyCompanies(userId);
		return propertyCompanies.stream().anyMatch(company -> company.getId().equals(propertyCompanyId));
	}

	@Override
	public boolean hasAssignPermission(Long userId, Long propertyCompanyId) throws Exception {
		log.info("检查用户分配权限，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);

		// 超级管理员拥有所有权限
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		if (dataScopeInfo.isSuperAdmin()) {
			log.info("用户{}是超级管理员，拥有分配权限", userId);
			return true;
		}

		// 物业公司管理员拥有本公司分配权限
		boolean hasPropertyCompanyPermission = permissionCacheService.hasPropertyCompanyPermission(userId,
				propertyCompanyId);
		log.info("用户{}物业公司权限检查结果：{}", userId, hasPropertyCompanyPermission);

		return hasPropertyCompanyPermission;
	}

	@Override
	public PropertyCompany getByCompanyCode(String companyCode) throws Exception {
		log.info("根据公司编码查询物业公司，公司编码：{}", companyCode);
		try {
			QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("company_code", companyCode);
			return this.getOne(queryWrapper);
		} catch (Exception e) {
			log.warn("根据公司编码查询物业公司失败，公司编码：{}", companyCode, e);
			return null;
		}
	}

	@Override
	public boolean hasPropertyCompanyPermission(Long userId, Long propertyCompanyId) throws Exception {
		log.info("检查用户是否有物业公司权限，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);
		try {
			// 检查是否为超级管理员
			DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
			if (dataScopeInfo.isSuperAdmin()) {
				return true;
			}

			// 检查用户是否有该物业公司的权限
			List<PropertyCompany> propertyCompanies = getUserPropertyCompanies(userId);
			return propertyCompanies.stream().anyMatch(company -> company.getId().equals(propertyCompanyId));
		} catch (Exception e) {
			log.warn("检查用户物业公司权限失败，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId, e);
			return false;
		}
	}

	@Override
	public List<PropertyCompany> getUserPropertyCompanies(Long userId) throws Exception {
		log.info("获取用户关联的物业公司列表，用户ID：{}", userId);
		try {
			List<Long> propertyCompanyIds = propertyCompanyDataScopeService.getUserPropertyCompanyIds(userId);

			if (propertyCompanyIds.isEmpty()) {
				return new ArrayList<>();
			}

			QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("id", propertyCompanyIds);
			return this.list(queryWrapper);
		} catch (Exception e) {
			log.warn("获取用户关联的物业公司列表失败，用户ID：{}", userId, e);
			return new ArrayList<>();
		}
	}

	/**
	 * 获取用户关联的物业公司列表（内部方法）
	 */
	private List<PropertyCompany> getUserPropertyCompaniesInternal(Long userId) {
		try {
			log.info("获取用户关联的物业公司列表，用户ID：{}", userId);
			List<Long> propertyCompanyIds = propertyCompanyDataScopeService.getUserPropertyCompanyIds(userId);

			if (propertyCompanyIds.isEmpty()) {
				return new ArrayList<>();
			}

			QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("id", propertyCompanyIds);
			return this.list(queryWrapper);
		} catch (Exception e) {
			log.warn("获取用户关联的物业公司列表失败，用户ID：{}", userId, e);
			return new ArrayList<>();
		}
	}

	@Override
	public boolean isCompanyCodeExists(String companyCode, Long excludeId) throws Exception {
		QueryWrapper<PropertyCompany> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("company_code", companyCode);

		if (excludeId != null) {
			queryWrapper.ne("id", excludeId);
		}

		return this.count(queryWrapper) > 0;
	}

	/**
	 * 转换为VO对象
	 */
	private PropertyCompanyVO convertToVO(PropertyCompany propertyCompany) {
		PropertyCompanyVO vo = new PropertyCompanyVO();
		BeanUtils.copyProperties(propertyCompany, vo);

		// 设置状态名称
		vo.setStatusName(getStatusName(propertyCompany.getStatus()));
		vo.setAuditStatusName(getAuditStatusName(propertyCompany.getAuditStatus()));

		return vo;
	}

	/**
	 * 获取状态名称
	 */
	private String getStatusName(Integer status) {
		if (status == null)
			return "";
		switch (status) {
		case 0:
			return "禁用";
		case 1:
			return "启用";
		default:
			return "未知";
		}
	}

	/**
	 * 获取审核状态名称
	 */
	private String getAuditStatusName(Integer auditStatus) {
		if (auditStatus == null)
			return "";
		switch (auditStatus) {
		case 0:
			return "待审核";
		case 1:
			return "审核通过";
		case 2:
			return "审核拒绝";
		case 3:
			return "审核拒绝";
		default:
			return "未知";
		}
	}

	@Override
	public Object getPropertyCompanyDetailStats(Long propertyCompanyId) throws Exception {
		log.info("获取物业公司详情统计信息，物业公司ID：{}", propertyCompanyId);
		try {
			// 检查物业公司是否存在
			PropertyCompany propertyCompany = this.getById(propertyCompanyId);
			if (propertyCompany == null) {
				throw new RuntimeException("物业公司不存在");
			}

			// 检查权限
			Long currentUserId = SecurityUtils.getCurrentUserId();
			if (!hasViewPermission(currentUserId, propertyCompanyId)) {
				throw new RuntimeException("您没有权限查看该物业公司的统计信息");
			}

			Map<String, Object> stats = new HashMap<>();

			// 1. 关联社区数
			List<PropertyCompanyCommunity> communities = propertyCompanyCommunityService
					.getPropertyCompanyCommunities(propertyCompanyId);
			stats.put("communityCount", communities.size());

			// 2. 员工数量（物业公司用户数量）
			// 前端会从用户列表API的total字段获取，这里不再计算
			// stats.put("employeeCount", 0);

			// 3. 服务房户数（根据关联社区→楼栋→单元→房户的层级关系计算）
			long householdCount = 0;
			if (!communities.isEmpty()) {
				List<Long> communityIds = communities.stream().map(PropertyCompanyCommunity::getCommunityId)
						.collect(Collectors.toList());

				// 调用区域服务获取房户数量
				try {
					// 这里应该调用区域服务的Feign接口获取房户统计
					// 暂时使用模拟数据
					householdCount = communityIds.size() * 100; // 假设每个社区100户
				} catch (Exception e) {
					log.warn("获取房户统计失败，使用默认值", e);
					householdCount = 0;
				}
			}
			stats.put("householdCount", householdCount);

			// 4. 本月收入（暂时使用模拟数据）
			stats.put("monthlyIncome", 0);

			log.info("获取物业公司详情统计信息成功，物业公司ID：{}，统计结果：{}", propertyCompanyId, stats);
			return stats;

		} catch (Exception e) {
			throw new RuntimeException("获取统计信息失败：" + e.getMessage());
		}
	}

	@Override
	@GlobalTransactional
	public void updateOrAddUserPropertyCompany(Long userId, Long propertyCompanyId) throws Exception {
		UserPropertyCompany upc = userPropertyCompanyMapper.selectByUserIdAndPropertyCompanyId(userId, propertyCompanyId);
		Long currentUserId = SecurityUtils.getCurrentUserId();
		LocalDateTime now = LocalDateTime.now();
		if (upc == null) {
			upc = new UserPropertyCompany();
			upc.setUserId(userId);
			upc.setCreateBy(currentUserId);
			upc.setCreateTime(now);
		}
		upc.setUpdateBy(currentUserId);
		upc.setUpdateTime(now);
		upc.setStatus(SystemStatusEnum.ENABLED.getCode());
		upc.setJoinDate(now.toLocalDate());
		upc.setPropertyCompanyId(propertyCompanyId);
		
		// 更新或插入
		if (upc.getId() == null) {
			userPropertyCompanyMapper.insert(upc);
			log.info("插入用户和物业公司关联，用户：{}，物业公司：{}", userId, propertyCompanyId);
		} else {
			userPropertyCompanyMapper.updateById(upc);
			log.info("更新用户和物业公司关联，用户：{}，物业公司：{}", userId, propertyCompanyId);
		}
	}
}
